package crp.core.portal.domain.services;

import crp.core.portal.domain.messages.PortalMessages;
import crp.core.portal.domain.models.PortalBannerEntity;
import com.qwlabs.storage.models.StorageObject;
import crp.core.portal.domain.repositories.PortalBannerRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class PortalBannerEditor {
    private final PortalBannerRepository bannerRepository;

    @Inject
    public PortalBannerEditor(PortalBannerRepository portalSectionRepository) {
        this.bannerRepository = portalSectionRepository;
    }

    public PortalBannerEntity create(StorageObject cover, String referenceUrl) {
        PortalBannerEntity entity = new PortalBannerEntity();
        entity.setCover(cover);
        entity.setReferenceUrl(referenceUrl);
        bannerRepository.persist(entity);
        return entity;
    }

    public boolean deleteById(String id) {
        return bannerRepository.deleteById(id);
    }

    public PortalBannerEntity update(String id, StorageObject cover, String referenceUrl) {
        return bannerRepository.findByIdOptional(id)
                .map(entity -> {
                    entity.setReferenceUrl(referenceUrl);
                    entity.setCover(cover);
                    bannerRepository.persist(entity);
                    return entity;
                })
                .orElseThrow(() -> PortalMessages.INSTANCE.sectionNotFound(id));
    }
}
